<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/dist/index.css'
interface ResourceItem {
  id: number
  name: string
  url: string
  categoryId: number
  description: string
  createdTime: string
}

const allResources = ref<ResourceItem[]>([])
const form = reactive({
  name: '',
  url: '',
  categoryId: '',
  current: 1,
  size: 10
})
// 2021010507 黄铄
const getResourcePages = async () => {
  try {
    const response = await fetch('/boss/resource/getResourcePages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'your_access_token_here' // Replace with actual token
      },
      body: JSON.stringify(form)
    })
    const data = await response.json()
    if (data.code === '000000') {
      allResources.value = data.data.records || []
      ElMessage.success('获取资源页面信息成功！')
    } else {
      ElMessage.error('获取资源页面信息失败！')
    }
  } catch (error) {
    console.error('Error fetching resources:', error)
    ElMessage.error('获取资源页面信息失败！')
  }
}
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '重要提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // Replace with your actual delete API call
    const response = await fetch(`/boss/resource/${id}`, { method: 'DELETE' })
    const data = await response.json()
    if (data.code === '000000') {
      ElMessage.success('删除资源成功！')
      getResourcePages()
    } else {
      ElMessage.error('删除资源失败！')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error deleting resource:', error)
      ElMessage.error('删除资源失败！')
    }
  }
}

const handleSearch = () => {
  form.current = 1 // Reset to first page when searching
  getResourcePages()
}

const handleReset = () => {
  Object.assign(form, {
    name: '',
    url: '',
    categoryId: '',
    current: 1,
    size: 10
  })
  getResourcePages()
}

const formatDate = (dateString: string | null | undefined) => {
  if (!dateString) return 'N/A'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

onMounted(() => {
  getResourcePages()
})
</script>

<template>
  <el-card class="box-card">

    <el-form
      :model="form"
      label-width="auto"
    >
      <el-form-item label="资源名称">
        <el-input
          v-model="form.name"
          placeholder="请输入资源名称"
        />
      </el-form-item>

      <el-form-item label="资源路径">
        <el-input
          v-model="form.url"
          placeholder="请输入资源路径"
        />
      </el-form-item>

      <el-form-item
        label="资源分类"
        style="width: 300px;"
      >
        <el-select
          v-model="form.categoryId"
          placeholder="请选择资源类别"
        >
          <el-option
            label="类别一"
            value="1"
          />
          <el-option
            label="类别二"
            value="2"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="handleSearch"
        >搜索查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="card-header">
      <el-button
        @click="$router.push('/resources/create')"
      >添加资源</el-button>
      <el-button
        @click="$router.push('/categories')"
      >资源类别</el-button>
    </div>
    <el-table
      :data="allResources"
      border
      style="width: 100%"
    >
      <el-table-column
        label="序号"
        width="80"
        type="index"
        align="center"
      />
      <el-table-column
        prop="name"
        label="资源名称"
        align="center"
      />
      <el-table-column
        prop="url"
        label="资源路径"
        align="center"
      />
      <el-table-column
        prop="description"
        label="描述"
        align="center"
      />
      <el-table-column
        prop="createdTime"
        label="添加时间"
        width="180"
        align="center"
      >
        <template #default="scope">
          {{ formatDate(scope.row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <template #default="scope">
          <el-button
            type="primary"
            @click="$router.push({ name: 'resource-edit', params: { id: scope.row.id } })"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            @click="handleDelete(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!-- 2021010507 黄铄 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="form.current"
        v-model:page-size="form.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400"
        @size-change="getResourcePages"
        @current-change="getResourcePages"
      />
    </div>
  </el-card>
</template>

<style scoped>
.box-card {
  width: auto;
  margin: 20px;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
.el-table {
  margin-top: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>